import os
from typing import Optional
from fastapi import UploadFile
import uuid

# 上传文件存储目录
UPLOAD_DIR = "uploads"


def ensure_upload_dir_exists():
    """确保上传目录存在"""
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)


def save_uploaded_file(file: UploadFile) -> str:
    """保存上传的文件，返回文件路径"""
    # 确保上传目录存在
    ensure_upload_dir_exists()
    
    # 生成唯一文件名
    file_extension = os.path.splitext(file.filename)[1]
    unique_filename = f"{uuid.uuid4()}{file_extension}"
    
    # 完整文件路径
    file_path = os.path.join(UPLOAD_DIR, unique_filename)
    
    # 保存文件
    with open(file_path, "wb") as buffer:
        content = file.file.read()
        buffer.write(content)
    
    # 返回相对路径
    return unique_filename


def get_file_path(filename: str) -> str:
    """获取文件的完整路径"""
    return os.path.join(UPLOAD_DIR, filename)


def delete_file(filename: str) -> bool:
    """删除文件，如果文件存在并成功删除则返回True"""
    file_path = get_file_path(filename)
    if os.path.exists(file_path):
        try:
            os.remove(file_path)
            return True
        except Exception:
            return False
    return False